package com.gitee.ipo.controller.system;


import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gitee.ipo.common.base.BaseController;
import com.gitee.ipo.common.base.BaseResult;
import com.gitee.ipo.system.entity.search.IpoDocInfoSearch;
import com.gitee.ipo.system.entity.search.SearchRequest;
import com.gitee.ipo.system.entity.star.IpoDocUserStar;
import com.gitee.ipo.system.service.IpoDocInfoService;
import com.gitee.ipo.system.service.IpoDocUserStarService;
import org.frameworkset.elasticsearch.boot.BBossESStarter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/ipoSearch")
public class DocSearchController extends BaseController {


    @Autowired
    private IpoDocInfoService ipoDocInfoService;

    @Autowired
    private IpoDocUserStarService ipoDocUserStarService;

    @Autowired
    private BBossESStarter bbossESStarter;

    /**
     * 访问页面：信披检索页面
     *
     * @return 跳转至列表页面
     */
    @RequestMapping("index")
    public String index() {
        return "system/ipoSearch/index";
    }


    /**
     * 信披检索
     *
     * @param searchRequest 信披检索
     * @return
     */
    @GetMapping(value = "/search")
    @ResponseBody
    public BaseResult getUserList(SearchRequest searchRequest) {
        List<IpoDocInfoSearch> ipoDocList = ipoDocInfoService.getIpoDoc(searchRequest);
        if (!CollectionUtils.isEmpty(ipoDocList)) {
            return success("查询成功", ipoDocList, (int) ipoDocList.get(0).getSize());
        } else {
            return error("没有该信披数据");
        }
    }


    @GetMapping(value = "/saveIpoDoc")
    @ResponseBody
    public BaseResult getUserList() {
        String result = ipoDocInfoService.saveIpoDoc();
        return success("查询成功", result);
    }


    /**
     * 用户收藏
     *
     * @param ipoDocUserStar 用户收藏
     * @return
     */
    @PostMapping(value = "/saveStar")
    @ResponseBody
    public BaseResult saveStar(IpoDocUserStar ipoDocUserStar) {
        QueryWrapper<IpoDocUserStar> wrapper = new QueryWrapper<>();
        int loginId = StpUtil.getLoginIdAsInt();
        ipoDocUserStar.setUserId(loginId);
        wrapper.eq("user_id", loginId)
                .eq("doc_id", ipoDocUserStar.getDocId())
                .eq("is_delete", 0)
                .last("limit 1");

        IpoDocUserStar ipoDocUserStar1 = ipoDocUserStarService.getOne(wrapper);
        if (Objects.nonNull(ipoDocUserStar1)) {
            return error("你已收藏该信息");
        }

        IpoDocInfoSearch ipoDocOne = ipoDocInfoService.getIpoDocOne(ipoDocUserStar.getDocId() + "");
        ipoDocUserStar.setDigest(ipoDocOne.getDigest()).setTitle(ipoDocOne.getTitle()).setSeccode(ipoDocOne.getSecCode()).setSecname(ipoDocOne.getSecName());
        boolean save = ipoDocUserStarService.save(ipoDocUserStar);
        if (save) {
            return success("收藏成功");
        } else {
            return error("收藏失败");
        }
    }


    /**
     * 获取收藏信息
     *
     * @param page 当前页
     * @return
     */
    @GetMapping(value = "/getUserStar")
    @ResponseBody
    public BaseResult getUserStar(@RequestParam(defaultValue = "1") Integer page) {
        QueryWrapper<IpoDocUserStar> wrapper = new QueryWrapper<>();
        int loginId = StpUtil.getLoginIdAsInt();
        wrapper.eq("user_id", loginId)
                .eq("is_delete", 0)
                .orderBy(true, false, "update_time");

        IPage<IpoDocUserStar> ipage = new Page<>(page, 20);
        IPage<IpoDocUserStar> starIPage = ipoDocUserStarService.page(ipage, wrapper);
        List<IpoDocUserStar> records = starIPage.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            List<IpoDocUserStar> collect = records.stream()
                    .map(k -> k.setSecCodeStr(k.getSeccode() + "/" + k.getSecname()))
                    .map(k -> k.setUpdateTimeStr(simpleDateFormat.format(k.getUpdateTime())))
                    .collect(Collectors.toList());
            return success("查询成功！", collect, (int) starIPage.getPages());
        } else {
            return error("暂无收藏信息");
        }
    }


    /**
     * 删除用户收藏信息
     *
     * @param docId 信息id
     * @return
     */
    @PostMapping(value = "/delUserStar")
    @ResponseBody
    public BaseResult delUserStar(@RequestParam("docId") Long docId) {
        QueryWrapper<IpoDocUserStar> wrapper = new QueryWrapper<>();
        int loginId = StpUtil.getLoginIdAsInt();
        wrapper.eq("user_id", loginId)
                .eq("doc_id", docId);

        IpoDocUserStar ipoDocUserStar = new IpoDocUserStar();
        ipoDocUserStar.setIsDelete(1);
        boolean update = ipoDocUserStarService.update(ipoDocUserStar, wrapper);
        if (update) {
            return success("删除成功！");
        } else {
            return error("删除失败！");
        }
    }


    /**
     * 文件下载
     *
     * @param downPath 文件下载路径
     * @return
     */
    @RequestMapping(value = "/downloadFile")
    public void downloadFile(HttpServletResponse response, HttpServletRequest request, String downPath) {
        ipoDocInfoService.downloadFile(downPath, response, request);
    }


}
